package cn.qzzg.controller;

import cn.qzzg.common.ResultBean;
import cn.qzzg.enums.CodeEnum;
import cn.qzzg.pojo.User;
import cn.qzzg.service.UserService;
import cn.qzzg.util.JJWTTokenUtil;
import cn.qzzg.util.RedisUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    RedisUtil redisUtil;
    @Resource
    private UserService userService;


    @GetMapping("/queryById")
    public ResultBean<?> queryById(HttpServletRequest request) {
        return ResultBean.success(userService.findById(request.getAttribute("userId").toString()).getName());
    }

    @PostMapping("/register")
    public ResultBean<?> register(@RequestBody User user) {
        User user1 = userService.findByOpenId(user.getOpenId());
        if (user1 != null)
            return ResultBean.error(CodeEnum.USER_ERROR_A0111);
        else
            user.setUserId("User_" + UUID.randomUUID().toString().replace("-", "").substring(0, 8));
        return ResultBean.success(userService.saveOne(user));
    }

    @PostMapping("/login")
    public ResultBean<?> login(String openId) {
        User user = userService.findByOpenId(openId);
        if (user == null)
            return ResultBean.error(CodeEnum.USER_ERROR_A0201);
        String token = JJWTTokenUtil.createToken(user.getUserId());
        redisUtil.setHash("user_token", user.getUserId(), token, 10L, TimeUnit.MINUTES);
        return ResultBean.success(token);
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public ResultBean<?> logout(HttpServletRequest request) {
        redisUtil.delHash("user_token", request.getAttribute("userId").toString());
        return ResultBean.success();
    }
}
